package day11.test2;

import java.util.BitSet;

class BufferAread{
    private String d;
    private boolean isEmpty;//标记缓冲区是否为空  true为空    false为满
    private final Object lock=new Object();//需要锁同一个对象，修改不同的值的话

    public BufferAread(String d) {
        this.d = d;
        this.isEmpty = true;
    }

    //完成向缓冲区类BufferArea放入一个字符串的d的方法put方法
    public void put(String i) throws InterruptedException {
        synchronized (lock){
            while(isEmpty==false){//满
                lock.wait();
            }
            d=i;
            isEmpty=false;//满
            System.out.println("Producer Put: 产品"+d);
            lock.notify();
        }
    }

    //完成向缓冲区类BufferArea取出一个字符串的d的方法set方法
    public void set() throws InterruptedException {
        synchronized (lock){
            while(isEmpty==true){//空
                lock.wait();
            }
            isEmpty=true;//空
            System.out.println("Consumer Get: 产品"+d);
            lock.notify();
        }
    }
}

public class run {
    public static void main(String[] args) throws InterruptedException {
        BufferAread bufferAread=new BufferAread("1");
        for(int i=1;i<=6;i++)
        {
            int a=i;
            Thread thread1=new Thread(()->{
                try{
                    bufferAread.put(Integer.toString(a));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });

            Thread thread2=new Thread(()->{
                try{
                    bufferAread.set();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });

            thread1.start();
            Thread.sleep(1000);

            thread2.start();
            Thread.sleep(1000);
        }
    }
}
